package com.example.usercenter.sys.service;

import com.alibaba.fastjson.JSONObject;
import com.example.usercenter.common.base.BaseDao;
import com.example.usercenter.common.base.BaseService;
import com.example.usercenter.sys.dao.OrgDao;
import com.example.usercenter.sys.entity.Org;
import com.example.usercenter.sys.entity.OrgUser;
import com.example.usercenter.sys.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrgService extends BaseService<Org, Long> {
    @Autowired
    @SuppressWarnings("SpringJavaAutowiringInspection")
    private OrgDao orgDao;

    protected BaseDao<Org, Long> getDao(){
            return orgDao;
    }

    @Override
    public boolean insert(Org entity) {
        if(entity.getParent()!=null){
            Org parent = orgDao.get(entity.getParent().getId());
            if(parent != null){
                entity.setPath(parent.getPath()+parent.getId()+"/");
            }
        }
        if(entity.getPath() == null){
            entity.setPath("/");
        }
        return super.insert(entity);
    }

    @Override
    public boolean update(Org entity) {
        Org old = orgDao.get(entity.getId());
        String oldPath = old.getPath();
        if(entity.getParent()!=null){
            Org parent = orgDao.get(entity.getParent().getId());
            if(parent != null){
                entity.setPath(parent.getPath()+parent.getId()+"/");
            }
        }
        else{
            entity.setPath("/");
        }
        String newPath = entity.getPath();
        if(!oldPath.equals(newPath)){
            orgDao.updateChildrenPathByPath(entity.getId(), oldPath, newPath);
        }
        return super.update(entity);
    }

    @Override
    public boolean sensitiveUpdate(Org entity) {
        if(entity.getParent()!=null){
            Org old = orgDao.get(entity.getId());
            String oldPath = old.getPath();
            if(entity.getParent()!=null){
                Org parent = orgDao.get(entity.getParent().getId());
                if(parent != null){
                    entity.setPath(parent.getPath()+parent.getId()+"/");
                }
            }
            else{
                entity.setPath("/");
            }
            String newPath = entity.getPath();
            if(!oldPath.equals(newPath)){
                orgDao.updateChildrenPathByPath(entity.getId(), oldPath, newPath);
            }
        }
        return super.sensitiveUpdate(entity);
    }

    @Override
    public boolean delete(Long id) {
        orgDao.deleteUserOrg(id);
        return super.delete(id);
    }

    /**
     * 查询用户组织
     * */
    private List<Org> getOrgs(User entity){
        if(entity.getOrgUsers()!=null && entity.getOrgUsers().size()>0){
            String orgIds = String.join(",", entity.getOrgUsers().stream().map(item -> { return String.valueOf(item.getOrgId());}).collect(Collectors.toList()));
            JSONObject params = new JSONObject();
            params.put("ids", orgIds);
            return orgDao.query(params);
        }
        return new ArrayList<Org>();
    }

    /**
     * 根据用户信息和权限代码查询用户组织
     * */
    public List<Org> getOrgsByUser(User entity, String authCode){
        Set<Org> orgs = new HashSet<Org>();
        if(entity.getGroup().isPeerAuth()){
            if(entity.getGroup().isAutoAuth()){
                if(entity.getOrgUsers()!=null && entity.getOrgUsers().size()>0){
                    String orgIds = String.join(",", entity.getOrgUsers().stream().map(item -> { return String.valueOf(item.getOrgId());}).collect(Collectors.toList()));
                    JSONObject params = new JSONObject();
                    params.put("ids", orgIds);
                    orgs.addAll(orgDao.query(params));
                }
            }
            else if(!StringUtils.isEmpty(authCode)){
                orgs.addAll(orgDao.queryByUserIdAndCode(entity.getId(), authCode));
            }
        }
        if(entity.getGroup().isChildAuth()){
            if(entity.getGroup().isAutoAuth()){
                for(OrgUser ou : entity.getOrgUsers()){
                    JSONObject params = new JSONObject();
                    params.put("path", ou.getOrgId());
                    orgs.addAll(orgDao.query(params));
                }
            }
            else if(!StringUtils.isEmpty(authCode)){
                List<Org> list = orgDao.queryByUserIdAndCode(entity.getId(), authCode);
                for(Org o : list){
                    JSONObject params = new JSONObject();
                    params.put("path", o.getId());
                    orgs.addAll(orgDao.query(params));
                }
            }
        }
        List<Org> list = new ArrayList<>(orgs);
        Collections.sort(list, new Comparator<Org>() {
            @Override
            public int compare(Org o1, Org o2) {
                return (int) (o1.getId() - o2.getId());
            }
        });
        return list;
    }
}